import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/pages/home/index.dart';
import 'package:flutter_enjoy_plus/pages/mine/index.dart';
import 'package:flutter_enjoy_plus/utils/Emitter.dart';
import 'package:flutter_enjoy_plus/utils/tokenManager.dart';
class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    tokenManager.init();
    registerLogoutEvent();
  }
  void registerLogoutEvent() {
    eventBus.on<LogoutEvent>().listen((event) {
      Navigator.pushNamed(context, '/login');
    });
  }

    final List _tabbarList = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png',
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png',
    }
  ];
  updateCurrentIndex(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
  int _currentIndex = 0;
  // 第一种方案，性能更差，每次点击都会重新渲染
  // getTabbarContent() {
  //   if (_currentIndex == 0){
  //     return const HomePage();
  //   } else {
  //     return const MinePage();
  //   }
  // }
  // 第二种方案，性能更优，可以通过index指定渲染
  List<BottomNavigationBarItem> getBottomNavigationBarItems(){
    List<BottomNavigationBarItem> list = [];
    for (var item in _tabbarList ) {
      list.add(
        BottomNavigationBarItem(
          icon: Image.asset(item['icon'],width: 30,height: 30,),
          activeIcon: Image.asset(item['activeIcon'],width: 30,height: 30,),
          label: item['label']
        )
      );
    }
    return list;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 安全区组件
      body: SafeArea(
        child: IndexedStack(
          index: _currentIndex, 
          children: [const HomePage(),MinePage(currentIndex: _currentIndex,updateCurrentIndex:updateCurrentIndex)],
        )
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        items:getBottomNavigationBarItems(),
        selectedItemColor: const Color.fromRGBO(85, 147, 175,1),
        // selectedItemColor: const Color.fromARGB(1,85, 147, 175),
        unselectedItemColor: Colors.black,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        }
      )
    );
  }
}
